package online.foxnull2.foxmall.cart.interceptor;

import online.foxnull2.common.constant.AuthConstant;
import online.foxnull2.common.constant.CartConstant;
import online.foxnull2.common.vo.MemberRespVo;
import online.foxnull2.foxmall.cart.to.UserInfoTo;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new InheritableThreadLocal<>();

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {

        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthConstant.LOGIN_USER);
        if (!ObjectUtils.isEmpty(memberRespVo)) {
            userInfoTo.setUserId(memberRespVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (!ObjectUtils.isEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setExistInCookie(true);
                    break;
                }
            }
        }
        if (ObjectUtils.isEmpty(userInfoTo.getUserKey())) {
            String value = UUID.randomUUID().toString();
            userInfoTo.setUserKey(value);
        }
        threadLocal.set(userInfoTo);
        // Proceed in any case.
        return true;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, ModelAndView modelAndView) {

        UserInfoTo userInfoTo = threadLocal.get();
        if (Boolean.FALSE.equals(userInfoTo.getExistInCookie())) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("foxmall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_EXPIRY);
            response.addCookie(cookie);
        }
        threadLocal.remove();
    }
}
